import Vue from 'vue';  
import Vuex from 'vuex';  
import { login as loginApi } from '@/api/login'; // 导入后端登录请求  

Vue.use(Vuex);  

const store = new Vuex.Store({  
  state: {  
    isAuthenticated: !!localStorage.getItem('token'), // 从 localStorage 初始化认证状态  
    user: null,  
    token: localStorage.getItem('token') || null // 从 localStorage 初始化 token  
  },  
  mutations: {  
    SET_AUTH(state, status) {  
      state.isAuthenticated = status;  
    },  
    SET_USER(state, user) {  
      state.user = user;  
    },  
    SET_TOKEN(state, token) {  
      state.token = token; // 存储 token  
    }  
  },  
  actions: {  
    async login({ commit }, loginData) {  
      try {  
        const response = await loginApi(loginData); // 调用 API  
        if (response.data.success) {  
          commit('SET_AUTH', true);  
          commit('SET_USER', { username: loginData.username }); // 这里可以根据需要调整  
          localStorage.setItem('token', response.data.token); // 将 token 存储在 localStorage 中  
          commit('SET_TOKEN', response.data.token); // 保存 token  
          return Promise.resolve(response.data);  
        } else {  
          return Promise.reject(response.data.message);  
        }  
      } catch (error) {  
        return Promise.reject('登录请求失败');  
      }  
    },  
    logout({ commit }) {  
      localStorage.removeItem('token'); // 移除 token  
      commit('SET_AUTH', false);  
      commit('SET_USER', null);  
      commit('SET_TOKEN', null); // 清空 token  
    }  
  }  
});  

export default store;